import React, { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import apiService from '../utils/api.js'
import '../styles/playlist-detail.css'
import '../styles/pages.css'
import '../styles/artist-detail.css' // 复用一些样式

function PlaylistDetail({ playSong }) {
  const { id } = useParams() // 获取路由参数中的歌单ID
  const navigate = useNavigate()
  const [playlist, setPlaylist] = useState(null)
  const [songs, setSongs] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')



  // 获取歌单详情
  const fetchPlaylistDetail = async () => {
    setLoading(true)
    setError('')
    try {
      // 调用API获取歌单详情
      const response = await apiService.getPlaylistDetail(id)
      if (response.code === 200) {
        // 提取歌单信息和歌曲列表
        setPlaylist(response.data || {})
        setSongs(response.data?.songs || [])
      } else {
        throw new Error('歌单不存在')
      }
    } catch (err) {
      console.error('获取歌单详情失败:', err)
      setError(err.message || '获取歌单详情失败，请稍后再试')
      // 使用模拟数据作为备选
      setMockData()
    } finally {
      setLoading(false)
    }
  }

  // 生成模拟歌单详情数据
  const setMockData = () => {
    const mockData = {
      id: parseInt(id),
      name: `我的歌单${id}`,
      description: '这是一个用户创建的歌单',
      coverImageUrl: `https://via.placeholder.com/400?text=歌单${id}`,
      songCount: 10,
      createdAt: '2023-01-01T00:00:00Z'
    }
    
    const mockSongs = [
      { id: 1, title: '晴天', artist: '周杰伦', album: '叶惠美', coverImageUrl: 'https://via.placeholder.com/300', audio: '' },
      { id: 2, title: '海阔天空', artist: 'Beyond', album: '乐与怒', coverImageUrl: 'https://via.placeholder.com/300', audio: '' },
      { id: 3, title: '小幸运', artist: '田馥甄', album: '我的少女时代', coverImageUrl: 'https://via.placeholder.com/300', audio: '' },
      { id: 4, title: '南山南', artist: '马頔', album: '孤岛', coverImageUrl: 'https://via.placeholder.com/300', audio: '' },
      { id: 5, title: '夜曲', artist: '周杰伦', album: '十一月的萧邦', coverImageUrl: 'https://via.placeholder.com/300', audio: '' }
    ]
    
    setPlaylist(mockData)
    setSongs(mockSongs)
  }

  // 返回上一页
  const handleBack = () => {
    navigate(-1)
  }

  // 处理歌曲播放
  const handlePlaySong = (song) => {
    console.log('播放歌曲:', song)
    // 使用从父组件传递的playSong函数来实际播放歌曲
    if (playSong) {
      playSong(song)
    } else {
      alert(`正在播放: ${song.title}`)
    }
  }

  // 组件加载时获取数据
  useEffect(() => {
    fetchPlaylistDetail()
  }, [id])





  return (
    <div className="playlist-detail-page">
      {loading ? (
        // 加载状态
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      ) : error ? (
        // 错误状态
        <div className="error-container">
          <button className="back-button" onClick={handleBack}>返回</button>
          <p>{error}</p>
          <button onClick={fetchPlaylistDetail}>重试</button>
        </div>
      ) : (
        // 成功状态 - 显示歌单详情
        <>
          <button className="back-button" onClick={handleBack}>
            ← 返回
          </button>

          {/* 歌单信息区域 */}
          <div className="playlist-info-section">
            <div className="playlist-cover-large">
              <img 
                src={playlist.coverImageUrl} 
                alt={playlist.name}
              />
            </div>
            <div className="playlist-basic-info">
              <h1 className="playlist-name-large">{playlist.name}</h1>
              <div className="playlist-meta-info">
                <span>{playlist.songCount} 首歌曲</span>
                {playlist.createdAt && (
                  <span>创建于 {new Date(playlist.createdAt).toLocaleDateString('zh-CN')}</span>
                )}
              </div>
              <p className="playlist-description">{playlist.description || '暂无描述'}</p>
            </div>
          </div>

          {/* 歌曲列表 */}
          <div className="songs-section">
            <h2 className="section-title">歌曲 ({songs.length})</h2>
            <div className="songs-list">
              {songs.map((song, index) => (
                <div key={song.id} className="song-item">
                  <div className="song-rank">{index + 1}</div>
                  <div className="song-cover">
                    <img src={song.coverImageUrl} alt={song.title} />
                  </div>
                  <div className="song-info">
                    <div className="song-title">{song.title}</div>
                    <div className="song-album">{song.artist ? song.artist.name : '-'} · {song.album ? song.album.title : '-'}</div>
                  </div>
                  <div className="song-actions">
                    <button className="play-btn" onClick={() => handlePlaySong(song)}>
                      播放
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  )
}

export default PlaylistDetail